package internal

import (
	"t11Lib/t11Errors"
	"t11Lib/t11Model"
	"t11Lib/t11Util"
	"time"
	"亚太-iot-服务器/conf"
	"亚太-iot-服务器/models"
)


type AccountBiz struct{}

func (self AccountBiz) GetMqAccount(macAddr string) (*models.MqAccountInfo, t11Errors.T11Error) {
	if macAddr == "" {
		return nil, t11Errors.New("非法的Mac地址")
	}
	o, err := models.NewEmqOrmer()
	if err != nil {
		return nil, err
	}
	mqUser := &models.MqttUser{
		Created:     time.Now(),
		Username:    macAddr,
		Password:    t11Util.RandMd5(),
		Salt:        "",
		IsSuperuser: 0,
	}
	var ret *models.MqAccountInfo
	dbConn := &t11Model.DbConn{o}
	return ret, t11Model.Transacrtion(dbConn, func() t11Errors.T11Error {
		created, _, oerr := dbConn.ReadOrCreate(mqUser, "Username")
		if oerr != nil {
			return t11Errors.Wrap(oerr)
		}
		ret = &models.MqAccountInfo{
			Host:     conf.AppConfig.MqttHost,
			Port:     conf.AppConfig.MqttPort,
			UseSsl:   conf.AppConfig.MqttUseSsl,
			Username: mqUser.Username,
			Password: mqUser.Password,
		}
		if !created {
			return nil
		} else {
			//创建auth
			auth := &models.MqttAcl{
				Allow:    0,
				IpAddr:   "",
				Username: ret.Username,
				Access:   3,
				Topic:    "/" + ret.Username,
			}
			dbConn.Insert(auth)
			return nil
		}
	})
}

